import React, { useState } from 'react'
import { useDispatch } from 'react-redux'
import { Button, NavBar, Form, Input, List, Toast } from 'antd-mobile'
import styles from './index.module.scss'
import { login, getCode } from '@/store/actions/login'
import { LoginForm } from '@/types/data'
import { useHistory, useLocation } from 'react-router'
import { AxiosError } from 'axios'
import { InputRef } from 'antd-mobile/es/components/input'
import useCountDown from '@/hooks/useCountDown'

const Login = () => {
  // 登录操作获取token,登录页跳转至首页
  const dispatch = useDispatch()
  const history = useHistory()
  // token失效跳转回登录页后再次登录返回原页面
  const location = useLocation<{ from: string }>()
  const onFinish = async (values: LoginForm) => {
    try {
      await dispatch(login(values))
      Toast.show({
        content: '登录成功!'
      })
      if (location.state) {
        return history.replace(location.state.from)
      }
      history.push('/home')
    } catch (e) {
      // 类型断言
      const error = e as AxiosError<{ message: string }>
      let content = '登录失败!'
      if (error.response) {
        content = error.response.data.message
      }
      Toast.show({
        content: content
      })
    }
  }

  // 倒计时操作
  const [sendable, setSendable] = useState(true)
  const { count, start } = useCountDown(60, () => {
    setSendable(true)
  })

  // 验证码操作,发验证码
  const inputRef = React.useRef<InputRef>(null)
  // 获取form实例
  const [form] = Form.useForm()
  const onGetCode = async () => {
    // 判断手机号校验是否成功
    const hasError = form.getFieldError('mobile').length > 0
    console.log(form.getFieldError('mobile'), 111111)
    if (hasError) {
      inputRef.current!.focus()
    }
    // 拿到手机号
    const mobile = form.getFieldValue('mobile')
    try {
      await dispatch(getCode(mobile))
      Toast.show({
        content: '短信已发送!'
      })
      // 开启倒计时
      start()
      setSendable(false)
    } catch (e) {
      const error = e as AxiosError<{ message: string }>
      let content = '错误'
      if (error.response) {
        content = error.response.data.message
      }
      Toast.show({
        content: content
      })
    }
  }

  return (
    <div className={styles.root}>
      <NavBar />

      <div className="login-form">
        <h2 className="title">账号登录</h2>

        <Form
          form={form}
          initialValues={{ mobile: '13911111112', code: '246810' }}
          onFinish={onFinish}>
          <Form.Item
            name="mobile"
            className="login-item"
            rules={[
              { required: true, message: '请输入手机号!' },
              { pattern: /^1\d{10}$/, message: '请输入正确格式的手机号!' }
            ]}>
            <Input placeholder="请输入手机号" ref={inputRef} />
          </Form.Item>
          <List.Item
            className="login-code-extra"
            extra={
              <span
                onClick={sendable ? onGetCode : undefined}
                className="code-extra">
                {sendable ? '发送验证码' : `${count}秒之后再发`}
              </span>
            }>
            <Form.Item
              name="code"
              rules={[
                { required: true, message: '请输入验证码' },
                { pattern: /^\d{6}$/, message: '请输入6为验证码!' }
              ]}
              className="login-item">
              <Input placeholder="请输入验证码" autoComplete="off" />
            </Form.Item>
          </List.Item>

          <Form.Item noStyle>
            <Button
              block
              type="submit"
              color="primary"
              className="login-submit">
              提交
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}
export default Login
